
$(function(){
    var isLogin = urls.checklogin();
    if(!isLogin) {
        $('.alert-title').html('未登录，请先登录');
        var $dialog = $('.modal-alert');
        $dialog.show();
        $dialog.find('.weui_btn_dialog').unbind('click').bind('click', function () {
            location.href = '../login';          
        });
        setTimeout(function(){
            location.href = '../login';
        }, 3000);
        return;
    }
    Page.token = urls.GetQueryString('t');
    $('a.homepage').attr('href', '../home?t=' + Page.token);

    Page.id = urls.GetQueryString('key');

    $('.select-main-img').click(function(){
        $('.input-main-img').click();
    })
    $('.select-old-img').click(function(){
        $('.input-old-img').click();
    })
    $('.mask .head .sure').click(Page.uploadImg);
    $('.mask .head .cancel').click(Page.cancelUpload);
    $('.delete-img').click(Page.removeImg);
    $('.mark-main-img').click(Page.markMainImg);

    Page.loadImgs();
    Page.loadMoto();


    var $image = $('.img-container > img'),
    options = {
      aspectRatio: 16 / 9,
      minContainerWidth: 300
    };
    $image.cropper(options);

    // Import image
    var $inputImage = $('#image_file'),
        URL = window.URL || window.webkitURL,
        blobURL;

    // if (URL) {
    //   $inputImage.change(function () {
    //     var files = this.files,
    //         file;

    //     if (files && files.length) {
    //       file = files[0];

    //       if (/^image\/\w+$/.test(file.type)) {
    //         blobURL = URL.createObjectURL(file);
    //         $image.one('built.cropper', function () {
    //           URL.revokeObjectURL(blobURL); // Revoke when load complete
    //         }).cropper('reset', true).cropper('replace', blobURL);
    //         $inputImage.val('');
    //         $('.mask').show();
    //       } else {
    //         showMessage('Please choose an image file.');
    //       }
    //     }
    //   });
    // } else {
    //   $inputImage.parent().remove();
    // }
});

var Page = {
    id: false,
    name: false,
    parent_id: false,
    parent_name: false
};

Page.initCss = function() {
    var bodyWidth = Page.getWindowWidth();
    var bodyHeight = Page.getWindowHeight();
}

Page.loadImgs = function() {
    $('.main-img ul').html('');
    $('.old-img ul').html('');
    var url = urls.server + '/bikes/' + Page.id + '/images';
    $.ajax({
        type: 'GET',
        async: true,
        url: url,
        dataType: 'json',
        success: function(e){
            if(!e || e.length < 1) {
                return;
            }
            var h = '', h_o = '';
            var data_level = e;
            for( var i=0, len=data_level.length; i<len; i++ ) {
                var item = data_level[i];
                if(item.category == '1') {
                    h += '<li class="li-img" data-id="'+ item.id +'"" data-cat="1"';
                    if( item.main_pic == '1' ) {
                        h += ' data-main="true"';
                    }
                    h += '  ><div>';
                    h += '      <img src="'+ urls.server + '/' +item.image_url +'">';
                    h += '      <div class="mname">'+ item.name +'</div>';
                    h += '  </div>';
                    h += '</li>'
                }
                else {
                    h_o += '<li class="li-img" data-id="'+ item.id +'" data-cat="0"';
                    if( item.main_pic == '1' ) {
                        h_o += ' data-main="true"';
                    }
                    h_o += '  ><div>';
                    h_o += '      <img src="'+ urls.server + '/' +item.image_url +'">';
                    h_o += '      <div class="mname">'+ item.name +'</div>';
                    h_o += '  </div>';
                    h_o += '</li>'
                }
            }

            $('.main-img ul').html(h);
            $('.old-img ul').html(h_o);

            $('li.li-img').click(function(){
                $('.delete-img').attr({
                    'data-id': $(this).attr('data-id'),
                    'data-cat': $(this).attr('data-cat')
                });
                $('.mark-main-img').attr(
                    {
                        'data-id': $(this).attr('data-id'),
                        'data-cat': $(this).attr('data-cat')
                    }
                );
                Page.showMask();
                $('#mask_action_sheet').show();
            });
        }
    });
}
Page.loadMoto = function(){
    var url = urls.server + '/bikes/' + Page.id;
    $.ajax({
        type: 'GET',
        async: true,
        url: url,
        dataType: 'json',
        data: {
            id: Page.id
        },
        success: function(e){
            if(e && e.id) {
                $('.moto-name').html(e.name);
            }
        }
    });    
}


Page.cancelUpload = function() {
    $('.img-container > img').cropper('destroy').cropper({
        aspectRatio: 16 / 9
    });
    $('.mask').hide();
}
Page.uploadImg = function() {
    var canvas_o = $('.img-container > img').cropper("getCroppedCanvas");
    var image=new Image();
    image.src = canvas_o.toDataURL();
    var w = 320;
    var h = 320 * image.height / image.width;

    var canvas=$('<canvas width="'+w+'" height="'+h+'"></canvas>')[0];
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0,0,w,h);  
    ctx.drawImage(image, 0, 0, w, h, 0, 0, w, h); 
    $(document.body).append(canvas);

    var data = canvas.toDataURL();  
    data = data.split(',')[1];   
    data = window.atob(data);   
    var ia = new Uint8Array(data.length);   
    for (var i = 0; i < data.length; i++) {   
        ia[i] = data.charCodeAt(i);   
    };   
    var blob = new Blob([ia], {   
        type: "image/png"  
    });
    var fd = new FormData();   
    fd.append('myFile', blob);  
    fd.append('id', Page.id);  
    fd.append('access_token', 'AABBCCDD');  

    $.ajax({
        url: urls.server + '/bikes/' + Page.id + '/images/upload',
        type: 'POST',
        data: fd,
        // contentType: false, 
        processData: false, 
        success: function(e){
            if(e && e.action == 'success') {
                $.ajax({
                    type: 'POST',
                    async: true,
                    url: urls.server + '/bikes/' + Page.id + '/images',
                    dataType: 'json',
                    data: {
                        moto_bike_id: Page.id,
                        name: name,
                        category: '1',
                        main_pic: '0',
                        access_token: 'AABBCCDD'
                    },
                    success: function(e){
                        Page.loadImgs();
                    }
                });
            }
        }
    })
}


Page.showMask = function() {
    var mask = $('#mask_action_sheet');
    var weuiActionsheet = $('#weui_actionsheet');
    weuiActionsheet.addClass('weui_actionsheet_toggle');
    mask.show()
        .focus()
        .addClass('weui_fade_toggle').one('click', function () {
        Page.hideActionSheet(weuiActionsheet, mask);
    });
    $('#actionsheet_cancel').one('click', function () {
        Page.hideActionSheet(weuiActionsheet, mask);
    });
    mask.unbind('transitionend').unbind('webkitTransitionEnd');
}
Page.hideActionSheet = function() {
    var weuiActionsheet = $('#weui_actionsheet');
    var mask = $('#mask_action_sheet');
    weuiActionsheet.removeClass('weui_actionsheet_toggle');
    mask.removeClass('weui_fade_toggle');
    mask.on('transitionend', function () {
        mask.hide();
    }).on('webkitTransitionEnd', function () {
        mask.hide();
    })
}


function fileSelectHandler(me) {

    /*var files = this.files, file;

    if (files && files.length) {
      file = files[0];

      if (/^image\/\w+$/.test(file.type)) {
        blobURL = URL.createObjectURL(file);
        $image.one('built.cropper', function () {
          URL.revokeObjectURL(blobURL); // Revoke when load complete
        }).cropper('reset', true).cropper('replace', blobURL);
        $inputImage.val('');
      } else {
        showMessage('Please choose an image file.');
      }
    }

    return;*/
    $('input[name="id"]').val(Page.id);
    $("#form_upload_main_img")
    .attr('action', urls.server + '/bikes/' + Page.id + '/images/upload')
    .ajaxSubmit(function(e) { 
        e = JSON.parse(e);
        if(e && e.action == 'success') {
            Page.postImgs(me, me.files.length-1, '1')
        }
    });
}
Page.postImgs = function(me, index, main) {
    var name = Page.getImageName() + '.' + me.files[index].type.replace('image/', '');
    $.ajax({
        type: 'POST',
        async: true,
        url: urls.server + '/bikes/' + Page.id + '/images',
        dataType: 'json',
        data: {
            moto_bike_id: Page.id,
            name: name,
            category: main,
            main_pic: '0',
            access_token: 'AABBCCDD'
        },
        success: function(e){
            index--;
            if(index > -1) {
                Page.postImgs(me, index, main)
            }
            else {
                Page.loadImgs();  
                me.files = [];              
            }
        }
    });
}

function fileSelectOldHandler(me) {

    /*var files = this.files, file;

    if (files && files.length) {
      file = files[0];

      if (/^image\/\w+$/.test(file.type)) {
        blobURL = URL.createObjectURL(file);
        $image.one('built.cropper', function () {
          URL.revokeObjectURL(blobURL); // Revoke when load complete
        }).cropper('reset', true).cropper('replace', blobURL);
        $inputImage.val('');
      } else {
        showMessage('Please choose an image file.');
      }
    }

    return;*/
    var name = Page.getImageName() + '.' + me.files[0].type.replace('image/', '');
    $('input[name="id"]').val(Page.id);
    $("#form_upload_old_img")
    .attr('action', urls.server + '/bikes/' + Page.id + '/images/upload')
    .ajaxSubmit(function(e) { 
        e = JSON.parse(e);
        if(e && e.action == 'success') {
            Page.postImgs(me, me.files.length-1, '0')
        }
    });
}

Page.getImageName = function() {
    var chars = ['0','1','2','3','4','5','6','7','8','9'];
    var res = "";
    for(var i = 0; i < 31 ; i ++) {
        var id = Math.ceil(Math.random()*9);
        res += chars[id];
    }
    return res;
}

Page.removeImg = function() {
    var me = $(this);
    var id = me.attr('data-id');
    var cat = me.attr('data-cat');
    if(!id) {
        return;
    }
    Page.hideActionSheet();

    $('.weui_dialog_confirm').show();
    $('.btn-cancel-delete-img').unbind('click').click(function(){
        $('.weui_dialog_confirm').hide()        
    })
    $('.btn-delete-img').unbind('click').click(function(){
        var url = urls.server + '/bikes/' + Page.id + '/images/' + id;
        $.ajax({
            type: 'DELETE',
            async: true,
            url: url,
            dataType: 'json',
            data: {
                id: Page.id,
                access_token: 'AABBCCDD'
            },
            success: function(e){
                if(e && e.action == 'success') {
                    $('.weui_dialog_confirm').hide();
                    $('li[data-id="'+ id +'"][data-cat="'+ me.attr('data-cat') +'"]').remove();

                    $('#toast').show();
                    setTimeout(function () {
                        $('#toast').hide();
                    }, 2000);
                }
            }
        });  
    })
}


Page.markMainImg = function(){
    var me = $(this);
    var id = me.attr('data-id');
    if(!id) {
        return;
    }
    Page.hideActionSheet();
    var url = urls.server + '/bikes/' + Page.id + '/images/' + id;

    var main = $('li[data-cat="'+me.attr('data-cat')+'"][data-main="true"]');
    if(main && main.length > 0) {
        $.ajax({
            type: 'PUT',
            async: true,
            url: urls.server + '/bikes/' + Page.id + '/images/' + main.attr('data-id'),
            dataType: 'json',
            data: {
                id: main.attr('data-id'),
                access_token: 'AABBCCDD',
                main_pic: '0'
            },
            success: function(e){
                if(e && e.action == 'success') {
                    main.removeAttr('data-main');
                    Page.putImgeMain(me);
                }
            }
        });  
    }
    else {
        Page.putImgeMain(me);
    }
}
Page.putImgeMain = function(me) {
    var url = urls.server + '/bikes/' + Page.id + '/images/' + me.attr('data-id');
    $.ajax({
        type: 'PUT',
        async: true,
        url: url,
        dataType: 'json',
        data: {
            id: me.attr('data-id'),
            access_token: 'AABBCCDD',
            main_pic: '1'
        },
        success: function(e){
            if(e && e.action == 'success') {
                $('li[data-id="'+ me.attr('data-id') +'"][data-cat="'+ me.attr('data-cat') +'"]').attr('data-main', 'true');
                $('#toast').show();
                setTimeout(function () {
                    $('#toast').hide();
                }, 2000);
            }
        }
    });  
}





/**
 *
 * HTML5 Image uploader with Jcrop
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright 2012, Script Tutorials
 * http://www.script-tutorials.com/


// convert bytes into friendly format
function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

// check for selected crop region
function checkForm() {
    if (parseInt($('#w').val())) return true;
    $('.error').html('Please select a crop region and then press Upload').show();
    return false;
};

// update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
    $('#x1').val(e.x);
    $('#y1').val(e.y);
    $('#x2').val(e.x2);
    $('#y2').val(e.y2);
    $('#w').val(e.w);
    $('#h').val(e.h);
};

// clear info by cropping (onRelease event handler)
function clearInfo() {
    $('.info #w').val('');
    $('.info #h').val('');
};

function fileSelectHandler() {
    // get selected file
    var oFile = $('#image_file')[0].files[0];

    // hide all errors
    $('.error').hide();

    // check for image type (jpg and png are allowed)
    var rFilter = /^(image\/jpeg|image\/png)$/i;
    if (! rFilter.test(oFile.type)) {
        $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
        return;
    }

    // check for file size
    if (oFile.size > 2500000 * 1024) {
        $('.error').html('You have selected too big file, please select a one smaller image file').show();
        return;
    }

    // preview element
    var oImage = document.getElementById('preview');

    // prepare HTML5 FileReader
    var oReader = new FileReader();
        oReader.onload = function(e) {

        // e.target.result contains the DataURL which we can use as a source of the image
        oImage.src = e.target.result;
        oImage.onload = function () { // onload event handler

            // display step 2
            $('.mask').fadeIn(500);

            // display some basic image info
            var sResultFileSize = bytesToSize(oFile.size);
            $('#filesize').val(sResultFileSize);
            $('#filetype').val(oFile.type);
            $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);

            // Create variables (in this scope) to hold the Jcrop API and image size
            var jcrop_api, boundx, boundy;

            // destroy Jcrop if it is existed
            if (typeof jcrop_api != 'undefined') 
                jcrop_api.destroy();

            // initialize Jcrop
            $('#preview').Jcrop({
                minSize: [32, 32], // min crop size
                aspectRatio : 1, // keep aspect ratio 1:1
                bgFade: true, // use fade effect
                bgOpacity: .3, // fade opacity
                onChange: updateInfo,
                onSelect: updateInfo,
                onRelease: clearInfo
            }, function(){

                // use the Jcrop API to get the real image size
                var bounds = this.getBounds();
                boundx = bounds[0];
                boundy = bounds[1];

                // Store the Jcrop API in the jcrop_api variable
                jcrop_api = this;
            });
        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}
 */